﻿using System;
using System.IO;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace TestProject.Assessment
{
    [TestClass]
    public static class WorkAround
    {
        public class Helper
        {
            private readonly FileLogger fileLogger; //TODO: Prevent logger from overriding msbuild.log file

            public Helper()
            {
                fileLogger = new FileLogger();
            }

            public string DeployWebApplication(string projectName, string targetPath)
            {
                using (var projectCollection = new ProjectCollection())
                {
                    var currentDirectory = Directory.GetCurrentDirectory();
                    var projPath = Path.Combine(currentDirectory, string.Format(@"..\..\..\{0}\{0}.csproj", projectName));
                    var project = projectCollection.LoadProject(projPath);
                    var deploymentPath = Path.Combine(currentDirectory, targetPath);
                    project.SetProperty("PublishDestination", deploymentPath);
                    if (!project.Build("PublishToFileSystem", new[] {fileLogger}))
                        throw new ApplicationException(
                            string.Format(
                                @"MSBuild failed on 'PublishToFileSystem' target. See '{0}\msbuild.log' log for details",
                                currentDirectory));
                    return deploymentPath;
                }
            }
        }

        public static string DeployedOBoobsSitePath { get; private set; }
        public static string DeployedRssServicePath { get; private set; }

        [AssemblyInitialize]
        public static void Init(TestContext context)
        {
            var helper = new Helper();
            DeployedOBoobsSitePath = helper.DeployWebApplication(@"OBoobsWallpaper", "TargetSite");
            DeployedRssServicePath = helper.DeployWebApplication(@"StubRssService", "RssService");
        }

        [AssemblyCleanup]
        public static void CleanUp()
        {
            //Do final clean up here
        }
    }
}
